<?php

namespace App\Http\Middleware\CallingCards;

use App\Enums\Kms\UserErrorEnum;
use App\Error\CardingCards\UserError;
use App\Exceptions\Custom\ResponseHttpException;
use App\Exceptions\KfHttpResponseException;
use App\Models\FeishuCallingCard\FeishuCallingCard;
use App\Models\Kms\App\ClientsModel;
use App\Models\Kms\User\KmsUser;
use App\Service\CallingCards\CardService;
use Closure;
use Illuminate\Http\Request;
use Laravel\Passport\Passport;
use Lcobucci\JWT\Parser;

class FeishuAuth
{
    /**
     * 验证飞书用户是否登录
     * @param Request $request
     * @param Closure $next
     * @return \Illuminate\Http\JsonResponse|mixed
     */
    public function handle(Request $request, Closure $next)
    {
        if (auth('callingCardsFeishu')->check()) {
            return $next($request);
        } elseif (auth("kmsApi")->check()) {
//            if (auth("kmsApi")->user()->isExited) {
//                throw new KfHttpResponseException(UserError::USER_EXITED);
//            }

            $userMap = KmsUser::query()->where("rmsUserId", auth("kmsApi")->user()->rmsUserId)->get();
            if ($userMap->where("isExited", 0)->count() == 0) {
                throw new ResponseHttpException(UserErrorEnum::$USER_EXITED);
            }

            // 检测是否存在（不存在添加）
            CardService::addCallingCardByUserId(auth("kmsApi")->user()->rmsUserId);

            $clientId = (new Parser())->parse($request->bearerToken())->getClaim("aud");
            if (
                Passport::clientModel()::where("id", $clientId)->where("revoked", 0)->first()
                &&
                ClientsModel::query()->where("clientId", $clientId)
                            ->where("status", ClientsModel::STATUS_NORMAL)
                            ->first()
            ) {
                $fsUserId          = auth("kmsApi")->user()->userId;
                $fsCallingCardUser = FeishuCallingCard::query()->where("feishuId", $fsUserId)->first();
                if (!$fsCallingCardUser) {
                    throw new KfHttpResponseException(UserError::USER_NOT_EXISTS_IN_SYSTEM);
                }
                auth('callingCardsFeishu')->setUser(
                    auth('callingCardsFeishu')->getProvider()->retrieveById(
                        $fsCallingCardUser->id
                    )
                );
                return $next($request);
            }
        }
        return response()->json(['code' => 403, 'msg' => '尚未登录']);

    }
}
